#include "../../include/engine/BufferOut.h"


using namespace z_bufferout;

void BufferOut::outBufferAsBitmap(Bitmap& bitmap) const {
	// Bitmap rgbaBitmap = Bitmap(fb.height, fb.width);

	for (unsigned int i = 0; i < fbOut->height; i++) {
		for (unsigned int j = 0; j < fbOut->width; j++) {
			int stIndex = (i * fbOut->width + j) * 4;
			unsigned char a = fbOut->buffer[stIndex + 3];
			unsigned char r = fbOut->buffer[stIndex];
			unsigned char g = fbOut->buffer[stIndex + 1];
			unsigned char b = fbOut->buffer[stIndex + 2];

			Color color = Color(a, r, g, b);
			bitmap.SetPixel(j, i, color);
		}
	}
}

BufferOut* BufferOut::instance = nullptr;


BufferOut& BufferOut::getInstance() {
	if (BufferOut::instance == nullptr) {
		BufferOut::instance = new BufferOut();
	}
	return *BufferOut::instance;
}

void BufferOut::renderingOver() {
	if (fbOut->width == fbWait->width && fbOut->height == fbWait->height) {
		z_frameBuffer::FrameBuffer* temp;
		temp = fbOut;
		fbOut = fbWait;
		fbWait = temp;
	}
}

void BufferOut::synchronous() {

	fbOut->width = screenWidth;
	fbOut->height = screenHeight;

	fbWait->width = screenWidth;
	fbWait->height = screenHeight;
}

BufferOut::~BufferOut() {
	delete fbOut;
	delete fbWait;
}

BufferOut::BufferOut() {
	screenHeight = 0;
	screenWidth = 0;
	
	fbOut = new z_frameBuffer::FrameBuffer();
	fbWait = new z_frameBuffer::FrameBuffer();

	fbOut->initFrameBuffer(z_vector::Vector4f(0.0, 0.0, 0.0, 1.0));
	fbWait->initFrameBuffer(z_vector::Vector4f(0.0, 0.0, 0.0, 1.0));
	synchronous();
}

